﻿#region License
/*
Copyright (c) 2005-2011, CellAO Team

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the CellAO Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Usings...
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Reflection;
using System.Text;
using AO.Core;
using Config = AO.Core.Config.ConfigReadWrite;
using Cell.Core;
using NLog;
using NLog.Config;
using NLog.Targets;
//using NLog.Win32.Targets;
#endregion

namespace ChatEngine
{
    /// <summary>
    /// 
    /// </summary>
    public class Program
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            #region Console Texts...

            Assembly a = Assembly.GetExecutingAssembly();
            AssemblyName an = a.GetName();
            string assname = an.Name.ToString();
            string assversion = an.Version.ToString();

            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description + " " + AssemblyInfoclass.AssemblyVersion;
            ConsoleText ct = new ConsoleText();
            ct.TextRead("main.txt");
            Console.WriteLine("Loading " + AssemblyInfoclass.Title + "...");
            if (ismodified())
            {
                Console.WriteLine("Your " + AssemblyInfoclass.Title + " was compiled from modified source code.");
            }
            else
                if (ismixed())
                {
                    Console.WriteLine("Your " + AssemblyInfoclass.Title + " uses mixed SVN revisions.");
                }
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Using ISComm v1.0");
            Console.WriteLine("[OK]");
            Console.ResetColor();

            #endregion

            bool processedargs = false;
            Server ChatServer = new Server();

            #region ISComm Code Area...
            System.Console.WriteLine("[ISComm] Waiting for link...");

            #region NLog

            LoggingConfiguration config = new LoggingConfiguration();
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
            consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            FileTarget fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);
            fileTarget.FileName = "${basedir}/ChatEngineLog.txt";
            fileTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget);
            config.LoggingRules.Add(rule1);
            LoggingRule rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget);
            config.LoggingRules.Add(rule2);
            LogManager.Configuration = config;

            #endregion


            System.Net.IPAddress localISComm;

            try
            {
                // Local ISComm IP valid?
                localISComm = IPAddress.Parse(Config.Instance.CurrentConfig.ISCommLocalIP);
            }
            catch
            {
                // Fallback to ZoneIP
                localISComm = IPAddress.Parse(Config.Instance.CurrentConfig.ZoneIP);
            }


            if (!ZoneCom.Link(localISComm.ToString(), Config.Instance.CurrentConfig.CommPort, ChatServer))
            {
                System.Console.WriteLine("[ISComm] Unable to link to ZoneEngine. :(");
                return;
            }
            System.Console.WriteLine("[ISComm] Linked with ZoneEngine! :D");
            #endregion

            ChatServer.EnableTCP = true;
            ChatServer.EnableUDP = false;

            try { ChatServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP); }
            catch { ct.TextRead("ip_config_pharse_error.txt"); Console.ReadKey(); return; }
            try { ChatServer.UdpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP); }
            catch { ct.TextRead("ip_config_pharse_error.txt"); Console.ReadKey(); return; }

            ChatServer.TcpPort = Convert.ToInt32(Config.Instance.CurrentConfig.ChatPort);
            ChatServer.MaximumPendingConnections = 100;

            #region Console Commands
            //Andyzweb: I added checks for if the server is running or not
            //also a command called running that returns the status of the server
            //and added the Console.Write("\nServer Command >>"); to chatserver
            string consoleCommand;
            ct.TextRead("chat_consolecommands.txt");
            while (true)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            ThreadMgr.Start();
                            ChatServer.Start();
                        }
                    }
                    processedargs = true;
                }
                Console.Write("\nServer Command >>");
                consoleCommand = Console.ReadLine();
                switch (consoleCommand.ToLower())
                {
                    case "start":
                        if (ChatServer.Running)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Chat Server is already running");
                            Console.ResetColor();
                            break;
                        }
                        ThreadMgr.Start();
                        ChatServer.Start();
                        break;
                    case "stop":
                        if (!ChatServer.Running)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Chat Server is not running");
                            Console.ResetColor();
                            break;
                        }
                        ThreadMgr.Stop();
                        ChatServer.Stop();
                        break;
                    case "exit":
                        Process.GetCurrentProcess().Kill();
                        break;
                    case "running":
                        if (ChatServer.Running)
                        {
                            Console.WriteLine("Chat Server is Running");
                            break;
                        }
                        Console.WriteLine("Chat Server not Running");
                        break;
                    default:
                        ct.TextRead("chat_consolecmdsdefault.txt");
                        break;
                }
            }
            #endregion
        }
        public static bool ismodified()
        {
            string[] info = AssemblyInfoclass.Trademark.Split(';');
            return (info[1] == "1");
        }
        public static bool ismixed()
        {
            string[] info = AssemblyInfoclass.Trademark.Split(';');
            return (info[0] == "1");
        }

    }
}